package cors

import (
	"MoSkeleton/framework/core/config/properties_gin"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 允许跨域
func Next() gin.HandlerFunc {
	corsProperty := properties_gin.CorsProperty{
		AllowCors:                     true,
		AccessControlAllowHeaders:     "Access-Control-Allow-Headers,Authorization,User-Agent, Keep-Alive, Content-Type, X-Requested-With,X-CSRF-Token,AccessToken,Token",
		AccessControlAllowMethods:     "GET, POST, DELETE, PUT, PATCH, OPTIONS",
		AccessControlAllowOrigin:      "*",
		AccessControlExposeHeaders:    "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type",
		AccessControlMaxAge:           "86400",
		AccessControlAllowCredentials: true,
	}
	return NextByConfig(&corsProperty)
}

func NextByConfig(corsProperty *properties_gin.CorsProperty) gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", corsProperty.GetAccessControlAllowOrigin())
		c.Header("Access-Control-Allow-Headers", corsProperty.GetAccessControlAllowHeaders())
		c.Header("Access-Control-Allow-Methods", corsProperty.GetAccessControlAllowMethods())
		c.Header("Access-Control-Expose-Headers", corsProperty.GetAccessControlExposeHeaders())
		c.Header("Access-Control-Allow-Credentials", strconv.FormatBool(corsProperty.GetAccessControlAllowCredentials()))

		// 放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusAccepted)
		}
		c.Next()
	}
}
